<template>
  <div class="menu-create">
    <el-card>
      <div slot="header">
        课程名称
      </div>
      <el-tree :data="sections" :props="defaultProps" draggable :allow-drop="handleAllowDrop" @node-drop="handleSort">
        <div slot-scope="{ node, data }" class="inner">
          <span>{{ node.label }}</span>
          <span class="actions" v-if="data.sectionName">
            <el-button>编辑</el-button>
            <el-button type="info">添加课时</el-button>
            <el-button>状态</el-button>
          </span>
          <span class="actions" v-else>
            <el-button>编辑</el-button>
            <el-button type="success">上传视频</el-button>
            <el-button>状态</el-button>
          </span>
        </div>
      </el-tree>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getSectionAndLesson, saveOrUpdateSection, saveOrUpdateLesson } from '@/services/course-section'
export default Vue.extend({
  name: 'CourseSection',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      sections: [],
      defaultProps: {
        children: 'lessonDTOS',
        label (data: any) {
          return data.sectionName || data.theme
        }
      }
    }
  },
  created () {
    this.loadLession()
  },
  methods: {
    handleNodeClick (data: any) {
      console.log(data)
    },
    async loadLession () {
      const { data } = await getSectionAndLesson(this.courseId)
      this.sections = data.data
    },
    /**
     * draggingNode 拖动的节点
     * dropNode 放置的目标节点
     * type 放置的位置(prev: 目标节点前；inner: 目标节点中；next: 目标节点后)
     */
    handleAllowDrop (draggingNode: any, dropNode: any, type: any) {
      return draggingNode.data.sectionId === dropNode.data.sectionId && type !== 'inner'
    },
    async handleSort (dragNode: any, dropNode: any, type: string, event: any) {
      try {
        await Promise.all(dropNode.parent.childNodes.map((item: any, index: number) => {
          if (dragNode.data.lessonDTOS) {
            return saveOrUpdateSection({
              id: item.data.id,
              orderNum: index
            })
          } else {
            return saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index
            })
          }
        }))
        this.$message.success('排序成功')
      } catch (err) {
        console.log(err)
        this.$message.error('排序失败')
      }
    }
  }
})
</script>

<style lang="scss" scope>
.inner {
  flex: 1;
  display: flex;
  padding: 10px;
  justify-content: space-between;
  align-content: center;
  border-bottom: 1px solid #ebeef5;
}

::v-deep .el-tree-node__content {
  height: auto;
}
</style>
